package com.goodlearning.gloriamobile.customdialog;

import com.goodlearning.gloriamobile.R;
//import kr.goodlearning.android.gradebank.activities.GradeBank_Schedule_GradeBank_Schedule;
import com.goodlearning.gloriamobile.commons.Constants;
import com.goodlearning.gloriamobile.commons.Utils;
import com.goodlearning.gloriamobile.net.JsonRequestThread.INetSuccessCallback;
import com.goodlearning.gloriamobile.net.JsonServiceRequester;
//import kr.goodlearning.jobcaster.net.JsonServiceRequester;
import com.goodlearning.gloriamobile.net.JsonWrapper;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.os.Handler.Callback;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 로그인 관련 다이얼로그
 * @author rapty54
 *
 */
public class LoginDialog extends BaseDialog{
	
	public interface ILoginCallback {
		public boolean handleMessage(String userId, String userPw); 
	}
	
	private Button searchingIdPw;
	private EditText idEt;
	private EditText pwEt;
	private Button loginBtn;
	private CheckBox autoLoginCb;
	private ILoginCallback loginCallback;
	
	/**
	 * 모든 로그인시도는 이메서드를 통해 진행된다.
	 * @param context
	 * @param callBack
	 */
	public static void show(Context context, ILoginCallback loginCallback){
		if( ! checkLoginState(context) ){
			//항상로그인이 체크되었거나 최근 로그인 시도가 인정된적이 없다면 로그인 다이얼로그 출력.  
			new LoginDialog(context, loginCallback).show();
			
		}else{
			if(loginCallback != null ){
				loginCallback.handleMessage(
						Utils.getStringByPreference(context, Constants.PRE_STRING_USER_ID, "")
	    				, Utils.getStringByPreference(context, Constants.PRE_STRING_USER_PW, ""));
			}
		}
	}
	/**
	 * 보여져야할 View 에 대한 Inflate 
	 */
	@Override
	public void setContentView(int layoutResID) {
		super.setContentView(layoutResID);
		View view = LayoutInflater.from(getContext()).inflate(layoutResID, null);
		((LinearLayout) findViewById(R.id.dialog_body_linearLayout)).addView(view, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
	}
	
	private LoginDialog(Context context, ILoginCallback loginCallback) {
		
		super(context, R.layout.base_dialog_layout, null, true);
		
		View loginMainBody=(View)findViewById(R.id.include_login_dialog_body);
		View LeftButton=(View)findViewById(R.id.dialog_title_left_button);
		View RightButton=(View)findViewById(R.id.dialog_right_button);
		TextView titleText=(TextView)findViewById(R.id.dialog_title_TextView);
		
		titleText.setText("로그인");
		LeftButton.setVisibility(View.INVISIBLE);
		loginMainBody.setVisibility(View.VISIBLE);
		
		RightButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				try{
//				initSession(getContext());
				dismiss();
				
				}catch (Exception e) {
					
				}
			}
		});
		
		searchingIdPw = (Button) findViewById(R.id.dialog_search_Id_pw);
		idEt = (EditText) findViewById(R.id.dialog_login_email);
		pwEt = (EditText) findViewById(R.id.dialog_login_password);
		loginBtn = (Button) findViewById(R.id.dialog_login_bt);
		
		this.loginCallback = loginCallback;
//		Utils.getBooleanByPreference(context, Constants.PRE_BOOLEAN_CHECK_AUTO_LOGIN, false);
//		autoLoginCb.setChecked(Utils.getBooleanByPreference(context, Constants.PRE_BOOLEAN_CHECK_AUTO_LOGIN, false));
		

		
		//login시도
		loginBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				requestLogin();
			}
		});
		
		searchingIdPw.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				
			}
		});
	}
	@Override
	public void onBackPressed() {

//		super.onBackPressed();
		dismiss();
	}
//	/**
//	 * 로그인시도
//	 */
	private void requestLogin() {
		JsonServiceRequester.requestLogin(
				context
				, idEt.getText().toString()
				, pwEt.getText().toString()
				, new INetSuccessCallback() {
					@Override
					public void sendCallback(JsonWrapper jsonWrapper) {
//						jsonWrapper.showLog();
						JSONArray jsonArray= jsonWrapper.getRootArray();
						JSONObject jsonObj = (JSONObject)jsonArray.get(0);
						if( "0".equals( Utils.convertObjToString( jsonObj.get("RESULT") ) ) ){
							//로그인 성공
							Utils.setPreference(context, Constants.PRE_BOOLEAN_VALID_SESSION , true);
							Utils.setPreference(context, Constants.PRE_STRING_USER_ID, idEt.getText().toString());
							Utils.setPreference(context, Constants.PRE_STRING_USER_PW, pwEt.getText().toString());
							
//							//항상로그인 설정
//							if(autoLoginCb.isChecked()){
//								Utils.setPreference(context, Constants.PRE_BOOLEAN_CHECK_AUTO_LOGIN, true);
//								
//							}else{
//								Utils.setPreference(context, Constants.PRE_BOOLEAN_CHECK_AUTO_LOGIN, false);
//							}
							
							Toast.makeText(context, "로그인 되었습니다.", Toast.LENGTH_LONG).show();
							
							try {
								dismiss();
							} catch (Exception e) {
								// TODO: handle exception
							}
							
						}else{
							//로그인 실패
							initSession(context);
							Toast.makeText(context, "로그인에 실패하였습니다. ( ID및 PASSWORD를 확인하세요.) ", Toast.LENGTH_LONG).show();
						}
					}
				});
		
	}
	
	
	public static boolean checkLoginState(Context context) {
		return Utils.getBooleanByPreference(context, Constants.PRE_BOOLEAN_CHECK_AUTO_LOGIN, false) 
				|| Utils.getBooleanByPreference(context, Constants.PRE_BOOLEAN_VALID_SESSION, false);
	}
	
	@Override
	public void onDetachedFromWindow() {	
		if(loginCallback != null && checkLoginState(getContext()) ){
			loginCallback.handleMessage(
					Utils.getStringByPreference(context, Constants.PRE_STRING_USER_ID, "")
    				, Utils.getStringByPreference(context, Constants.PRE_STRING_USER_PW, ""));
		}
	}
	
	/**
	 * 모든 세션정보 초기화
	 * @param context
	 */
	public static void initSession(Context context) {
		Utils.setPreference(context, Constants.PRE_BOOLEAN_VALID_SESSION , false);
		Utils.setPreference(context, Constants.PRE_BOOLEAN_CHECK_AUTO_LOGIN, false);
		Utils.setPreference(context, Constants.PRE_STRING_USER_ID, null);
		Utils.setPreference(context, Constants.PRE_STRING_USER_PW, null);
	}
	
	
	public static void logout(Context context) {
		Utils.setPreference(context, Constants.PRE_BOOLEAN_VALID_SESSION , false);
	}

}
